package com.ffyc.cemp.services.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ffyc.cemp.common.dto.HttpResult;
import com.ffyc.cemp.dao.mapper.ICinemaMapper;
import com.ffyc.cemp.dao.mapper.IHallMapper;
import com.ffyc.cemp.dao.mapper.IMovieMapper;
import com.ffyc.cemp.dao.mapper.IScheduleMapper;
import com.ffyc.cemp.domain.entity.Cinema;
import com.ffyc.cemp.domain.entity.Hall;
import com.ffyc.cemp.domain.entity.Movie;
import com.ffyc.cemp.domain.entity.Schedule;
import com.ffyc.cemp.domain.vo.ScheduleVo;
import com.ffyc.cemp.services.service.IScheduleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ScheduleServiceImpl implements IScheduleService {

    @Autowired
    private IScheduleMapper scheduleMapper;
    @Autowired
    private IMovieMapper movieMapper;
    @Autowired
    private ICinemaMapper cinemaMapper;
    @Autowired
    private IHallMapper hallMapper;

    @Override
    public void addSchedule(Schedule schedule) {
        scheduleMapper.insert(schedule);
    }

    public Map<String, List<ScheduleVo>> findAllSchedule() {
        List<Schedule> schedules = scheduleMapper.selectList(null);
        Map<String, List<ScheduleVo>> map = new HashMap<>();

        for (Schedule s : schedules) {
            String key = new SimpleDateFormat("yyyy-MM-dd").format(s.getDate());
            Movie movie = movieMapper.selectById(s.getMovie());
            ScheduleVo scheduleVo = new ScheduleVo(movie, s);
            if (!map.containsKey(key)) {
                map.put(key, new ArrayList<ScheduleVo>() {
                    {
                        add(scheduleVo);
                    }
                });
            } else {
                map.get(key).add(scheduleVo);
            }
        }
        return map;
    }

    @Override
    public List<ScheduleVo> findScheduleByMovieId(int movieId) {
        LambdaQueryWrapper<Schedule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Schedule::getMovie, movieId);
        List<Schedule> schedules = scheduleMapper.selectList(queryWrapper);
        List<ScheduleVo> list = new ArrayList<>();

        for (Schedule schedule : schedules) {

            Date fDate = schedule.getDate();
            Date currDate = new Date();

            if (currDate.compareTo(fDate) > 0) continue;

            Integer mId = schedule.getMovie();
            Integer hallId = schedule.getHall();
            Integer cId = schedule.getCinema();
            ScheduleVo vo = new ScheduleVo(movieMapper.selectById(mId), schedule);
            vo.setHall(hallMapper.selectById(hallId));
            vo.setCinema(cinemaMapper.selectById(cId));
            list.add(vo);

        }

        return list;
    }
}
